package chu.dejian.ui.fragmet;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import chu.dejian.adapter.SendedRequestAdapter;
import chu.dejian.db.DBHelper;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.SendedRequestEntity;
import chu.dejian.models.GetSendedAttenderRequestResponse;
import chu.dejian.models.PostAttenderRequestRequest;
import chu.dejian.models.PostAttenderRequestResponse;
import chu.dejian.restApi.RestClient;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.NetUtil;
import com.sam.utils.display.DensityUtils;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.widget.listview.custom_menu_list.SwipeMenuItemListView;
import chu.dejian.ui.activity.AttentionApplyActivity;
import chu.dejian.widget.AttentionLevelView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AttentionSendedRequestFragment extends BaseFragment {
	private static AttentionSendedRequestFragment instance;
	private SendedRequestAdapter sendedRequestAdapter;
	private List<ContactEntity> sendedRequestList;
	private SwipeMenuItemListView sendedRequestListView;

	private AnsyncSendedRequestThread ansyncSendedRequestThread = new AnsyncSendedRequestThread();

	public synchronized static AttentionSendedRequestFragment getInstance(){
		if(instance == null){
			instance = new AttentionSendedRequestFragment();
		}
		return instance;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sendedRequestListView = new SwipeMenuItemListView(getActivity());
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
		sendedRequestListView.setLayoutParams(lp);
		Drawable sepratorLineDrawable = new ColorDrawable(getResources().getColor(R.color.separator_line_bg));
		sendedRequestListView.setDivider(sepratorLineDrawable);
		sendedRequestListView.setDividerHeight(1);
//		sendedRequestListView.setMenuCreator(creator);
//		sendedRequestListView.setOnMenuItemClickListener(onMenuItemClickListener);
//		refusedListView.setOnItemClickListener(onItemClickListener);
//		sendedRequestListView.setOnSwipeListener(onSwipeListener);
		sendedRequestList = SendedRequestEntity.convertToContactEntity(DBHelper.getInstance().getSendedRequestDao().getAllRequest());
		if(sendedRequestList == null) sendedRequestList = new ArrayList<>();
		sendedRequestAdapter = new SendedRequestAdapter(sendedRequestList);
		sendedRequestListView.setAdapter(sendedRequestAdapter);
		setContentView(sendedRequestListView);
	}

	@Override
	protected void findView() {}

	@Override
	protected void initView() {
	}

	@Override
	public void onResume() {
		super.onResume();
		newRefusedCounts = 0;
		if(NetUtil.checkNetWork(getActivity())) ansyncSendedRequestThread.start();
	}

	private boolean isAnsyncRequest = false;
	private static int newRefusedCounts = 0;
	public void AsyncSendedAttentionRequests(int startPage){

		if(isAnsyncRequest) return;
		isAnsyncRequest = true;

		RestClient.getAuthedClient().getApiService().getSendedAttenderRequest(startPage,new Callback<GetSendedAttenderRequestResponse>() {
			@Override
			public void success(GetSendedAttenderRequestResponse getSendedAttenderRequestResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取已发送的关注请求-getReceivedAttenderRequest》\n请求成功： \n\t返回数据：" + getSendedAttenderRequestResponse.toString());
				final List<GetSendedAttenderRequestResponse.ResultsEntity> resultEntities = getSendedAttenderRequestResponse.getResults();
				if (resultEntities == null || resultEntities.size() == 0) return;
				for(GetSendedAttenderRequestResponse.ResultsEntity resultsEntity : resultEntities){
					SendedRequestEntity sendedRequestEntity = GetSendedAttenderRequestResponse.toSendedRequestEntity(resultsEntity);
					DBHelper.getInstance().getSendedRequestDao().insertRequest(sendedRequestEntity);
					ContactEntity contactEntity = SendedRequestEntity.convertToContactEntity(sendedRequestEntity);
					if(!sendedRequestList.contains(contactEntity)){
						sendedRequestList.add(contactEntity);
						newRefusedCounts++;
					}
				}
				isAnsyncRequest = false;
				if(getSendedAttenderRequestResponse.getNext() != null && !getSendedAttenderRequestResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getSendedAttenderRequestResponse.getNext()).getQueryParameter("page"));
					AsyncSendedAttentionRequests(nextPage);
				} else if(newRefusedCounts > 0) {
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Log.d("SamLog","接收到的新请求个数为>>>>>>>>>>> " + newRefusedCounts);
							sendedRequestAdapter.notifyDataSetChanged();
						}
					});
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取已发送的关注请求-getReceivedAttenderRequest》\n请求失败： \n\t错误信息：" + retrofitError.toString());
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						T.showLong(getActivity(),R.string.get_data_from_webserver_failed);
					}
				});

			}
		});
	}

	class AnsyncSendedRequestThread implements Runnable {
		public boolean running = false;
		private Thread thread = null;

		public void run() {
			AsyncSendedAttentionRequests(1);
		}

		public void start() {
			try {
				this.thread = new Thread(this);
				this.running = true;
				this.thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
			} finally {
			}
		}
	}

}
